#include "serialporthandler.h"
#include "QSettings"
SerialPortHandler::SerialPortHandler()
{
    qDebug()<<"SerialPortHandler";
}

//SerialPortHandler::SerialPortHandler(QObject *parent)
//    : QObject(parent)
//{
//     //openPort();
//}

void SerialPortHandler::closePort()
{
    if (serialPort.isOpen()) {
        QString portName = serialPort.portName();
        serialPort.clear();
        serialPort.close();
        qDebug() << portName << "串口已关闭.";
        connectStatus = false;
    }
}
bool SerialPortHandler::openPort(int type, QString portName)//"topCameraLightNuberOf1"
{
    // 检查端口是否已经打开
    if (!serialPort.isOpen()) {
        qDebug() << "正在打开串口...\n";
    } else {
        qDebug() << "串口已打开，已连接成功.\n";
        return true;
    }

    QString dev = "";

    if(2 != type) {
        dev += "镜头:";
    } else {
        dev += "光源:";
    }

    dataType = type;
    QSettings settings("./config/systemConfig.ini", QSettings::IniFormat);
    settings.beginGroup("system");
    QString pName = settings.value(portName).toString();
    settings.endGroup();



    qDebug()<< dev + pName;
    serialPort.setPortName(pName); // 请替换为你的串口地址
    serialPort.setParity(QSerialPort::NoParity);

    serialPort.setDataBits(QSerialPort::Data8);
    if(2 != type)
    {
        serialPort.setBaudRate(QSerialPort::Baud115200);
    } else {
        serialPort.setBaudRate(QSerialPort::Baud19200);
    }

    serialPort.setStopBits(QSerialPort::OneStop);
    connect(&serialPort, &QSerialPort::readyRead, this, &SerialPortHandler::readData);
    connect(&timer, SIGNAL(timeout()), this, SLOT(readTimeOut()));

    if (!serialPort.isOpen()) {
        if(serialPort.open(QIODevice::ReadWrite))
        {
            qDebug() << "串口已打开.\n" ;
            connectStatus = true;
            return true;
        }
    }

    qDebug() << pName << " 打开失败: " << serialPort.errorString();

    return false;
}
SerialPortHandler::~SerialPortHandler()
{
    if (serialPort.isOpen()) {
        serialPort.clear();
        serialPort.close();
    }
}

bool SerialPortHandler::checkConnectState()
{
    if(sendCount >= packetLoss || sendCount == 0)
    {
        connectStatus = false;
    } else {
        connectStatus = true;
    }
    return connectStatus;
}


void SerialPortHandler::sendData(const QString &data)
{
    if (serialPort.isOpen()) {
        sendCount++;
        QByteArray requestData = data.toLatin1();
        qDebug()<<"serail: " << data;
        serialPort.write(requestData);
    }

}

void SerialPortHandler::sendData(QByteArray &arr)
{
    if (serialPort.isOpen()) {
        sendCount++;
        serialPort.write(arr);
    }
}

//void SerialPortHandler::requestData()
//{
//    sendData("SX#");
//}

void SerialPortHandler::readTimeOut()
{
    sendCount = 1;

    QByteArray responseData = serialPort.readAll();

    if(dataType == 2)
    {
        QString response(responseData);
        if (!response.isEmpty()) {
            qDebug() << "读取到数据：" << response;
            emit newQStringDataReceived(response);
        }
    }
    else{
        if (0 != responseData.length()) {
            qDebug() << "读取到数据：" << responseData;
            emit newQByteArrayDataReceived(responseData);
        }
    }
    timer.stop();
}
void SerialPortHandler::readData()
{ 
    timer.start(30);
}

bool SerialPortHandler::getConnectStatus() const
{
    return connectStatus;
}

void SerialPortHandler::setConnectStatus(bool value)
{
    connectStatus = value;
}


QString SerialPortHandler::sendDataSync(const QString &data)
{
    QByteArray requestData = data.toLatin1();
    serialPort.write(requestData);

    if (!serialPort.waitForBytesWritten(3000)) {
        qDebug() << "发送数据超时";
        return "";
    }

    if (!serialPort.waitForReadyRead(3000)) {
        qDebug() << "等待数据超时";
        return "";
    }

    QByteArray responseData = serialPort.readAll();
    QString response(responseData);
    qDebug() << "读取到数据：" << response;
    return response;
}
